package com.hc.api.utils;

import com.hc.comm.utils.StringUtil;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 分享相关的一些变量
 * Created by yx on 2017/4/24.
 */
public class ShareConfigUtils {
    private static String WXAppId = "wx00f7438bd83c1b79";
    private static String WxAppSecret = "dfa0c42ab892b26e258dd5ed2ac1b720";
    private static String WxBaseScope = "snsapi_base";
    private static String WxSNSScope = "snsapi_userinfo";
    private static String WxAuthURL = "https://api.weixin.qq.com/cgi-bin/token";
    private static String WxJsApiTicket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    private static String wxSmallSessionKeyUrl = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    public static String getWxJsApiTicketURL() {
        return WxJsApiTicket;
    }


    public static String getWXAppId() {
        return WXAppId;
    }

    public static String getWxAppSecret() {
        return WxAppSecret;
    }

    public static String getWxBaseScope() {
        return WxBaseScope;
    }

    public static String getWxSNSScope() {
        return WxSNSScope;
    }

    public static String getWxAuthURL() {
        return WxAuthURL;
    }

    /**
     * 获取微信分享授权
     */
    public static String getWXShareAuth() throws Exception {
        //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        String url = ShareConfigUtils.getWxAuthURL() + "?grant_type=client_credential&appid=" + WXAppId + "&secret=" + WxAppSecret;
        return HttpsUtil.requestGet(url);
    }

    /**
     * 获取微信授权的权限签名
     *
     * @param accessToken
     * @return
     * @throws Exception
     */
    public static String getWXJsApiTicket(String accessToken) throws Exception {
        if (StringUtil.isEmpty(accessToken)) {
            return "";
        }
        String url = ShareConfigUtils.getWxJsApiTicketURL() + "?access_token=" + accessToken + "&type=jsapi";
        return HttpsUtil.requestGet(url);
    }

    /**
     * 微信OAUTH授权
     *
     * @param wxCode 用户授权code
     * @return
     */
    public static String getWXOAUTHCode(String wxCode) throws Exception {
        if (StringUtil.isEmpty(wxCode)) {
            return "";
        }
        System.out.println("获取用户授权!");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + getWXAppId()
                + "&secret=" + getWxAppSecret()
                + "&code=" + wxCode + "&grant_type=authorization_code";
        System.out.println(url);
        return HttpsUtil.requestGet(url);
    }

    public static String getWXUserInfo(String accessToken, String openId) throws Exception {
        if (StringUtil.isEmpty(accessToken) || StringUtil.isEmpty(openId)) {
            return "";
        }
        System.out.println("获取用户信息!");
        String Url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        System.out.println(Url);
        return HttpsUtil.requestGet(Url);
    }

    public static Map<String, String> signWX(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    /**
     * 获取微信小程序通过code换取session_key
     *
     * @param loginCode //微信小程序登录时获取的code
     * @return
     * @throws Exception
     */
    public static String getWXSmallSessionKey(String loginCode) throws Exception {
        if (StringUtil.isEmpty(loginCode)) {
            return "";
        }
        String url = wxSmallSessionKeyUrl + "&appid=wx3f882f116bb7fef8&secret=7238386b8a9b1168df9ef4f0f471afbc&js_code=" + loginCode;
        return HttpsUtil.requestGet(url);
    }
}
